package org.circedroid.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


import org.circedroid.core.Data;
import org.circedroid.core.point;


public class CirceDroidActivity extends Activity {
	private TabHost th;
	private Spinner regdep;
	Data data;
	private Location dernierepos;
	private boolean locateme = false;
	private MenuItem locateitem = null;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menubase, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.locate:
	        	if (locateitem==null){
	        		locateitem = item;
	        	}
	        	if (locateme){
	        		if (locateitem!=null){locateitem.getIcon().setColorFilter(null);}
	        		locateme = false;
	        		locate();
	        	} else {
	        		if (locateitem!=null){locateitem.getIcon().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);}
	        		locateme = true;
	        		locate();
	        	}
	            return true;
	        case R.id.about:locateitem = item;
	        	AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
	    		builder1.setTitle("A propos")
	    				.setIcon(R.drawable.circe)
	    				.setMessage("Application développée par Thibault Coupin et Emmanuel Rosetti, ingénieurs de l'ENSG.\nInspiré du Programme Circé développé par l'IGN.\n \u00A9 2012") 
	    				.setCancelable(false)
	    				.setPositiveButton("Ok", 
	    						new DialogInterface.OnClickListener() {
	    							public void onClick(DialogInterface dialog, int id) {
	    								
	    								
	    							}
	    						})
	    				;
	    		AlertDialog alert1 = builder1.create();
	    		alert1.show();
	            return true;
	        case R.id.exit:
	        	AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
	    		builder2.setMessage("Voulez-vous vraiment quitter l'application?") 
	    				.setCancelable(false)
	    				.setPositiveButton("Oui", 
	    						new DialogInterface.OnClickListener() {
	    							public void onClick(DialogInterface dialog, int id) {
	    								CirceDroidActivity.this.finish();
	    							}
	    						})
	    				.setNegativeButton("Non",
	    						new DialogInterface.OnClickListener() {
	    							public void onClick(DialogInterface dialog, int id) {
	    								dialog.cancel();
	    							}
	    						});
	    		AlertDialog alert2 = builder2.create();
	    		alert2.show();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private LocationListener loclist= new LocationListener() {
		
		public void onStatusChanged(String provider, int status, Bundle extras) {
			
		}
		
		public void onProviderEnabled(String provider) {
			
		}
		
		public void onProviderDisabled(String provider) {
						
		}
		
		public void onLocationChanged(Location location) {
			if (locateme){
				dernierepos=location;
				if (location.getProvider().equals(LocationManager.GPS_PROVIDER)){
					if (locateitem!=null){locateitem.getIcon().setColorFilter(Color.GREEN,PorterDuff.Mode.MULTIPLY);}
				} else if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER)){
					if (locateitem!=null){locateitem.getIcon().setColorFilter(Color.RED,PorterDuff.Mode.MULTIPLY);}
				}
				applyLocation();
			}
		}
	};
	
	private void locate(){
		final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		if (!locateme){
			locationManager.removeUpdates(loclist);
			return;
		}
		
		boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		final String GpsProvider = LocationManager.GPS_PROVIDER;
		final String networkProvider = LocationManager.NETWORK_PROVIDER;
		if (isGPS)
		{
			if (locateitem!=null){locateitem.getIcon().setColorFilter(0xffff8800,PorterDuff.Mode.MULTIPLY);}
			locationManager.requestLocationUpdates(GpsProvider, 0,0, loclist);
		}
		else{
			AlertDialog.Builder builder3 = new AlertDialog.Builder(this);
    		builder3.setMessage("Voulez-vous utiliser le GPS ?") 
    				.setCancelable(false)
    				.setPositiveButton("Oui", 
    						new DialogInterface.OnClickListener() {
    							public void onClick(DialogInterface dialog, int id) {
    								if (locateitem!=null){locateitem.getIcon().setColorFilter(0xffff8800,PorterDuff.Mode.MULTIPLY);}
    								locationManager.requestLocationUpdates(GpsProvider, 0,0, loclist);
    								Toast.makeText(getApplicationContext(),
    										"Veuillez activer le GPS", Toast.LENGTH_SHORT).show();
    								startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
    					            
    							}
    						})
    				.setNegativeButton("Non",
    						new DialogInterface.OnClickListener() {
    							public void onClick(DialogInterface dialog, int id) {
    								locationManager.requestLocationUpdates(networkProvider, 0,0, loclist);
    								dialog.cancel();
    							}
    						});
    		AlertDialog alert3 = builder3.create();
    		alert3.show();
		}
		dernierepos=null;
	}
	
	private void applyLocation(){
		
		if(dernierepos!=null){
			regdep=(Spinner)findViewById(R.id.spinner_systdepart);
			for (int i=0;i<regdep.getAdapter().getCount();i++)
			{
				if(regdep.getItemAtPosition(i).toString().equals("WGS84"))
				{
					regdep.setSelection(i);
					break;
				}
			}
			Spinner typcoordep = (Spinner) findViewById(R.id.spinner_typcoorddep);
			typcoordep.setSelection(1);
			Spinner unitdep = (Spinner) findViewById(R.id.spinner_unitdep);
			updateunitprojdep();
			unitdep.setSelection(1);
			Spinner spmeri = (Spinner) findViewById(R.id.spinner_meriddep);
			spmeri.setSelection(0);
			updatealtidep();
			Spinner typealti = (Spinner) findViewById(R.id.spinner_altidep);

			EditText lon=(EditText)findViewById(R.id.lon1);
			EditText lat=(EditText)findViewById(R.id.lat1);
			EditText alt=(EditText)findViewById(R.id.h);
			lon.setText(Double.toString(dernierepos.getLongitude()));
			lat.setText(Double.toString(dernierepos.getLatitude()));
			alt.setText(Double.toString(dernierepos.getAltitude()));
			
			if (dernierepos.getProvider().equals(LocationManager.GPS_PROVIDER)){
				typealti.setSelection(1);
				
			} else {
				typealti.setSelection(0);
			}
		
			
		}
		updatecalc();

	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        data=new Data(getApplicationContext());
                
        setContentView(R.layout.main);
        
        th = (TabHost) findViewById(R.id.tabhost);
        th.setup();
        
        TabSpec spec1=th.newTabSpec("dep");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator("Départ", getResources().getDrawable(android.R.drawable.arrow_up_float));
        TabSpec spec2=th.newTabSpec("arr");
        spec2.setContent(R.id.tab2);
        spec2.setIndicator("Arrivée", getResources().getDrawable(android.R.drawable.arrow_down_float));
        TabSpec spec3=th.newTabSpec("cal");
        spec3.setContent(R.id.tab3);
        spec3.setIndicator("Calcul", getResources().getDrawable(android.R.drawable.ic_media_play));
        th.addTab(spec1);
        th.addTab(spec2);
        th.addTab(spec3);
        
        //Départ
        regdep = (Spinner) findViewById(R.id.spinner_systdepart);
        addItemOnRegDep();
        
        regdep.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				addItemOnRegArr();
				updateTypCoorddep();
				updateunitprojdep();
				updateTypCoordarr();
				updateunitprojarr();
				updatealti();
				updatecalc();
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
        
        
        Spinner altidep = (Spinner) findViewById(R.id.spinner_altidep);
        altidep.setOnItemSelectedListener(new OnItemSelectedListener(){
        	public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				Spinner altidep = (Spinner) findViewById(R.id.spinner_altidep);
				//TextView tvalti = (TextView) findViewById(R.id.h);
				LinearLayout llalti = (LinearLayout) findViewById(R.id.linearLayoutcalcalti);
				
				if (altidep.getSelectedItemId()==0){
					//tvalti.setEnabled(false);
					llalti.setVisibility(LinearLayout.GONE);
				}
				else {
					//tvalti.setEnabled(true);
					llalti.setVisibility(LinearLayout.VISIBLE);
				}
				
				updatealtiarr();
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
        }
		);
        
        Spinner regarr = (Spinner) findViewById(R.id.spinner_systarrivee);
        regarr.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				updateTypCoordarr();
				updateunitprojarr();
				updatealti();
				updatecalc();
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
        
        Spinner typcoordep = (Spinner) findViewById(R.id.spinner_typcoorddep);
        typcoordep.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				updateunitprojdep();
				updatealti();
				updatecalc();
				
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
        
        Spinner typcoorarr = (Spinner) findViewById(R.id.spinner_typcoordarr);
        typcoorarr.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				updateunitprojarr();
				updatealti();
				updatecalc();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
        
        Spinner unitdep = (Spinner) findViewById(R.id.spinner_unitdep);
    	unitdep.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				updatecalc();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
    
    	
    	Button buttoncalc = (Button) findViewById(R.id.buttoncalc);
    	final AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
    	buttoncalc.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
					point pdep=new point();
					point parr=new point();
					
					Spinner spinner_reg= (Spinner) findViewById(R.id.spinner_systdepart);
					pdep.setReg(data.getRegNum((String) spinner_reg.getSelectedItem()));
					Spinner spinner_typcoord= (Spinner) findViewById(R.id.spinner_typcoorddep);
					String selecttypcoor=(String) spinner_typcoord.getSelectedItem();
					if (selecttypcoor.equals(getResources().getString(R.string.typecoordcart))){
						pdep.setTypcoor(1);
					}
					else if (selecttypcoor.equals(getResources().getString(R.string.typecoordgeo))){
						pdep.setTypcoor(2);
					}
					else if (selecttypcoor.equals(getResources().getString(R.string.typecoordplan))){
						pdep.setTypcoor(3);
					}
					
					switch (pdep.getTypcoor()) {
					case 1: 
						EditText etx= (EditText) findViewById(R.id.X);
						EditText ety= (EditText) findViewById(R.id.Y);
						EditText etz= (EditText) findViewById(R.id.Z);
						pdep.setX(Double.parseDouble(etx.getText().toString()));
						pdep.setY(Double.parseDouble(ety.getText().toString()));
						pdep.setZ(Double.parseDouble(etz.getText().toString()));
						break;
					case 2:
						Spinner spinner_unit = (Spinner) findViewById(R.id.spinner_unitdep);
						String selectunit=(String) spinner_unit.getSelectedItem();
						String[] listunit=getResources().getStringArray(R.array.unitarray);
						for (int i=0;i<listunit.length;i++){
							Log.d("moi", Integer.toString(i));
							if (listunit[i].equals(selectunit)){
								pdep.setUnit(i+1);
								Log.d("moi", "monunit");
								break;
							}
						}
						Spinner spinner_lgo = (Spinner) findViewById(R.id.spinner_meriddep);
						pdep.setLgo(data.getLgoNum((String) spinner_lgo.getSelectedItem()));
						EditText etlon1= (EditText) findViewById(R.id.lon1);
						EditText etlat1= (EditText) findViewById(R.id.lat1);
						EditText etlon21= (EditText) findViewById(R.id.lon21);
						EditText etlat21= (EditText) findViewById(R.id.lat21);
						EditText etlon22= (EditText) findViewById(R.id.lon22);
						EditText etlat22= (EditText) findViewById(R.id.lat22);
						EditText etlon31= (EditText) findViewById(R.id.lon31);
						EditText etlat31= (EditText) findViewById(R.id.lat31);
						EditText etlon32= (EditText) findViewById(R.id.lon32);
						EditText etlat32= (EditText) findViewById(R.id.lat32);
						EditText etlon33= (EditText) findViewById(R.id.lon33);
						EditText etlat33= (EditText) findViewById(R.id.lat33);
						double lon;
						double lat;
						switch (pdep.getUnit()) {
						case 1:
							pdep.setLon(Double.parseDouble(etlon1.getText().toString()));
							pdep.setLat(Double.parseDouble(etlat1.getText().toString()));
							break;
						case 2:
							pdep.setLon(Double.parseDouble(etlon1.getText().toString())*Math.PI/180.0);
							pdep.setLat(Double.parseDouble(etlat1.getText().toString())*Math.PI/180.0);
							break;
						case 3:
							pdep.setLon(Double.parseDouble(etlon1.getText().toString())*Math.PI/200.0);
							pdep.setLat(Double.parseDouble(etlat1.getText().toString())*Math.PI/200.0);
							break;
						case 4:
							pdep.setLon(Double.parseDouble(etlon1.getText().toString())*Math.PI/12.0);
							pdep.setLat(Double.parseDouble(etlat1.getText().toString())*Math.PI/12.0);
							break;
						case 5:
							pdep.setLon(Double.parseDouble(etlon1.getText().toString())*Math.PI/648000.0);
							pdep.setLat(Double.parseDouble(etlat1.getText().toString())*Math.PI/648000.0);
							break;
						case 6:
							pdep.setLon(Double.parseDouble(etlon1.getText().toString())*Math.PI/43200.0);
							pdep.setLat(Double.parseDouble(etlat1.getText().toString())*Math.PI/43200.0);
							break;
						case 10:
							lon=Double.parseDouble(etlon31.getText().toString())+Double.parseDouble(etlon32.getText().toString())/60.0+Double.parseDouble(etlon33.getText().toString())/3600.0;
							lat=Double.parseDouble(etlat31.getText().toString())+Double.parseDouble(etlat32.getText().toString())/60.0+Double.parseDouble(etlat33.getText().toString())/3600.0;
							pdep.setLon(lon*Math.PI/180.0);
							pdep.setLat(lat*Math.PI/180.0);
							break;
						case 11:
							lon=Double.parseDouble(etlon31.getText().toString())+Double.parseDouble(etlon32.getText().toString())/60.0+Double.parseDouble(etlon33.getText().toString())/3600.0;
							lat=Double.parseDouble(etlat31.getText().toString())+Double.parseDouble(etlat32.getText().toString())/60.0+Double.parseDouble(etlat33.getText().toString())/3600.0;
							pdep.setLon(lon*Math.PI/12.0);
							pdep.setLat(lat*Math.PI/12.0);
							break;
						case 12:
							lon=Double.parseDouble(etlon21.getText().toString())+Double.parseDouble(etlon22.getText().toString())/60.0;
							lat=Double.parseDouble(etlat21.getText().toString())+Double.parseDouble(etlat22.getText().toString())/60.0;
							pdep.setLon(lon*Math.PI/180.0);
							pdep.setLat(lat*Math.PI/180.0);
							break;
						}
						pdep.setLon(pdep.getLon()+data.listLGO.get(pdep.getLgo()).getValue());
						break;
					case 3:
						Spinner spinner_proj = (Spinner) findViewById(R.id.spinner_projdep);
						pdep.setProj(data.getProjNum((String) spinner_proj.getSelectedItem()));
						EditText ete = (EditText) findViewById(R.id.E);
						EditText etn = (EditText) findViewById(R.id.N);
						pdep.setEasting(Double.parseDouble(ete.getText().toString()));
						pdep.setNorthing(Double.parseDouble(etn.getText().toString()));
						break;
					}
					
					
					//Composante verticale
					if (pdep.getTypcoor()!=1){
						Spinner spinnerreadep = (Spinner) findViewById(R.id.spinner_altidep);
						String selectalti=spinnerreadep.getSelectedItem().toString();
					
						EditText etalti = (EditText) findViewById(R.id.h);
					
						if (selectalti.equals(getResources().getString(R.string.noinfo))){
							pdep.setRea(-1);
							
						}
						else if (selectalti.equals(getResources().getString(R.string.he))){
							pdep.setH(Double.parseDouble(etalti.getText().toString()));
						}
						else {
							pdep.setRea(data.getReaNum(selectalti));
							pdep.setHa(Double.parseDouble(etalti.getText().toString()));
						}
					}
					
					
					spinner_reg= (Spinner) findViewById(R.id.spinner_systarrivee);
					parr.setReg(data.getRegNum((String) spinner_reg.getSelectedItem()));
					spinner_typcoord= (Spinner) findViewById(R.id.spinner_typcoordarr);
					
					selecttypcoor=(String) spinner_typcoord.getSelectedItem();
					if (selecttypcoor.equals(getResources().getString(R.string.typecoordcart))){
						parr.setTypcoor(1);
					}
					else if (selecttypcoor.equals(getResources().getString(R.string.typecoordgeo))){
						parr.setTypcoor(2);
					}
					else if (selecttypcoor.equals(getResources().getString(R.string.typecoordplan))){
						parr.setTypcoor(3);
					}
					
					switch (parr.getTypcoor()) {
					case 1: //rien à faire
						
						break;
					case 2:
						Spinner spinner_unit = (Spinner) findViewById(R.id.spinner_unitarr);
						String selectunit=(String) spinner_unit.getSelectedItem();
						String[] listunit=getResources().getStringArray(R.array.unitarray);
						for (int i=0;i<listunit.length;i++){
							if (listunit[i].equals(selectunit)){
								parr.setUnit(i+1);
								break;
							}
						}
						Spinner spinner_lgo = (Spinner) findViewById(R.id.spinner_meridarr);
						parr.setLgo(data.getLgoNum((String) spinner_lgo.getSelectedItem()));
						break;
					case 3:
						Spinner spinner_proj = (Spinner) findViewById(R.id.spinner_projarr);
						parr.setProj(data.getProjNum((String) spinner_proj.getSelectedItem()));
						break;
					}
					
					//Composante verticale
					if (parr.getTypcoor()!=1){
						Spinner spinnerreaarr = (Spinner) findViewById(R.id.spinner_altiarr);
						String selectaltiarr=spinnerreaarr.getSelectedItem().toString();
						if (selectaltiarr.equals(getResources().getString(R.string.noinfo))){
							parr.setRea(-1);
							
						}
						else if (selectaltiarr.equals(getResources().getString(R.string.he))){
				
						}
						else {
							parr.setRea(data.getReaNum(selectaltiarr));
							
						}
					}
					
					
					/////////////////////////////
					//ICI CONVERSION
					parr.convertFrom(pdep, data);
					/////////////////////////////
					
					double lonmin=0;
					double lonmax=0;
					double latmin=0;
					double latmax=0;
					switch (data.listZNE.get(pdep.getReg()).getUnit()) {
					case 2:
						lonmin=data.listZNE.get(pdep.getReg()).getLonMin()*Math.PI/180.0;
						lonmax=data.listZNE.get(pdep.getReg()).getLonMax()*Math.PI/180.0;
						latmin=data.listZNE.get(pdep.getReg()).getLatMin()*Math.PI/180.0;
						latmax=data.listZNE.get(pdep.getReg()).getLatMax()*Math.PI/180.0;
						break;
					case 3:
						lonmin=data.listZNE.get(pdep.getReg()).getLonMin()*Math.PI/200.0;
						lonmax=data.listZNE.get(pdep.getReg()).getLonMax()*Math.PI/200.0;
						latmin=data.listZNE.get(pdep.getReg()).getLatMin()*Math.PI/200.0;
						latmax=data.listZNE.get(pdep.getReg()).getLatMax()*Math.PI/200.0;
						break;
					}
					if (pdep.getLon()>lonmax || pdep.getLon()<lonmin || pdep.getLat()>latmax || pdep.getLat()<latmin){
						Toast.makeText(getApplicationContext(), "Conversion hors zone d'application.", Toast.LENGTH_LONG).show();
					}
					//else {
		    		builder1.setTitle("Résultats :")
		    				.setMessage(parr.toString(data)) 
		    				.setCancelable(false)
		    				.setPositiveButton("Ok", 
		    						new DialogInterface.OnClickListener() {
		    							public void onClick(DialogInterface dialog, int id) {
		    								
		    							}
		    						})
		    				;
		    		AlertDialog alert1 = builder1.create();
		    		alert1.show();

					//}
			}
		});

    	
    }
    	
public void addItemOnRegDep(){
    	Spinner spinnerDep=(Spinner) findViewById(R.id.spinner_systdepart);
    	
    	List<String> list = new ArrayList<String>();
    	Set<Integer> regset=data.listREG.keySet();
		Iterator<Integer> iter=regset.iterator();
		Integer current;
		for (int i=0;i<data.listREG.size();i++){
			current=iter.next();
			list.add(data.listREG.get(current).getNom());
		}
		
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerDep.setAdapter(dataAdapter);
		
		
		
    }
public void addItemOnRegArr(){
    
    	
    	Spinner spinnerDep=(Spinner) findViewById(R.id.spinner_systdepart);
    	String regdep=spinnerDep.getSelectedItem().toString();
    	Spinner spinnerArr=(Spinner) findViewById(R.id.spinner_systarrivee);
    	String selectedregarr;
    	try {
    		selectedregarr=spinnerArr.getSelectedItem().toString();
    	}
    	catch (Exception e){
    		selectedregarr="";
    	}
    	
    	List<String> list = new ArrayList<String>();
    	Set<Integer> regset=data.listREG.keySet();
    	Iterator<Integer> iter=regset.iterator();
		Integer current;
		list.add(regdep);
		
		//on cherche le num reg de départ
		int numregdep=0;
		for (int i=0;i<data.listREG.size();i++){
			current=iter.next();
			if (data.listREG.get(current).getNom()==regdep){
				numregdep=current;
				break;
			}
		}
		
		//On regarde les transfo de syst
		for (int j=1;j<=data.listTSG.size();j++){
			if (data.listTSG.get(j).getReg1()==numregdep){
				list.add(data.listREG.get(data.listTSG.get(j).getReg2()).getNom());
			}
			if (data.listTSG.get(j).getReg2()==numregdep){
				list.add(data.listREG.get(data.listTSG.get(j).getReg1()).getNom());
			}
		}
		
		//On regarde les transfo de syst par grille
		for (int j=1;j<=data.listTSG0.size();j++){
			if (data.listTSG0.get(j).getReg1()==numregdep){
				list.add(data.listREG.get(data.listTSG0.get(j).getReg2()).getNom());
			}
			if (data.listTSG0.get(j).getReg2()==numregdep){
				list.add(data.listREG.get(data.listTSG0.get(j).getReg1()).getNom());
			}
		}

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerArr.setAdapter(dataAdapter);
		
		if (list.contains(selectedregarr)){
			spinnerArr.setSelection(list.indexOf(selectedregarr));
		}
		else {
			spinnerArr.setSelection(0);
		}
		
    }

public void updateTypCoorddep(){
    	
    	Spinner spinnerDep=(Spinner) findViewById(R.id.spinner_systdepart);
    	String regdep=spinnerDep.getSelectedItem().toString();
		Spinner spdep=(Spinner) findViewById(R.id.spinner_typcoorddep);
		String selectedtype;
    	try {
    		selectedtype=spdep.getSelectedItem().toString();
    	}
    	catch (Exception e){
    		selectedtype="";
    	}
    	List<String> list = new ArrayList<String>();
    	
    	//on cherche le num reg de dà©part
    	Set<Integer> regset=data.listREG.keySet();
    	Iterator<Integer> iter=regset.iterator();
		Integer current;
		int numregdep=0;
		for (int i=0;i<data.listREG.size();i++){
			current=iter.next();
			if (data.listREG.get(current).getNom()==regdep){
				numregdep=current;
				break;
			}
		}
		if (data.listTYPCOOR.get(numregdep).getCart()){
			list.add(getString(R.string.typecoordcart));
		}
		if (data.listTYPCOOR.get(numregdep).getGeo()){
			list.add(getString(R.string.typecoordgeo));
		}
		if (data.listTYPCOOR.get(numregdep).getPlan()){
			list.add(getString(R.string.typecoordplan));
		}
		
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spdep.setAdapter(dataAdapter);
		
		if (list.contains(selectedtype)){
			spdep.setSelection(list.indexOf(selectedtype));
		}
		else {
			spdep.setSelection(0);
		}

    }
public void updateTypCoordarr(){
    	
    	Spinner spinnerDep=(Spinner) findViewById(R.id.spinner_systarrivee);
    	String regdep=spinnerDep.getSelectedItem().toString();
		Spinner spdep=(Spinner) findViewById(R.id.spinner_typcoordarr);
		String selectedtype;
    	try {
    		selectedtype=spdep.getSelectedItem().toString();
    	}
    	catch (Exception e){
    		selectedtype="";
    	}
    	List<String> list = new ArrayList<String>();
    	
    	//on cherche le num reg de départ
    	Set<Integer> regset=data.listREG.keySet();
    	Iterator<Integer> iter=regset.iterator();
		Integer current;
		int numregdep=0;
		for (int i=0;i<data.listREG.size();i++){
			current=iter.next();
			if (data.listREG.get(current).getNom()==regdep){
				numregdep=current;
				break;
			}
		}
		if (data.listTYPCOOR.get(numregdep).getCart()){
			list.add(getString(R.string.typecoordcart));
		}
		if (data.listTYPCOOR.get(numregdep).getGeo()){
			list.add(getString(R.string.typecoordgeo));
		}
		if (data.listTYPCOOR.get(numregdep).getPlan()){
			list.add(getString(R.string.typecoordplan));
		}
		
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spdep.setAdapter(dataAdapter);
		
		if (list.contains(selectedtype)){
			spdep.setSelection(list.indexOf(selectedtype));
		}
		else {
			spdep.setSelection(0);
		}
    }

public void updateunitprojdep(){
	Spinner spdep = (Spinner) findViewById(R.id.spinner_typcoorddep);
	Spinner unitdep = (Spinner) findViewById(R.id.spinner_unitdep);
	LinearLayout llunit = (LinearLayout) findViewById(R.id.linearLayoutUnitdep);
	LinearLayout llproj = (LinearLayout) findViewById(R.id.linearLayoutprojectiondep);
	if (spdep.getSelectedItem().toString()==getString(R.string.typecoordgeo)){
		//afficher unit, cacher proj
		llunit.setVisibility(LinearLayout.VISIBLE);
		llproj.setVisibility(LinearLayout.GONE);
		//mise à  jour des unités
		Spinner spregdep=(Spinner) findViewById(R.id.spinner_systdepart);
		String reg=spregdep.getSelectedItem().toString();
		String selectedunit;
		try {
			selectedunit=unitdep.getSelectedItem().toString();
		}
		catch (Exception e){
			selectedunit="";
		}
		List<String> list = new ArrayList<String>();
		int numreg=data.getRegNum(reg);
		HashMap<Integer, Integer> listUnit=data.listUNIT.get(numreg).getListUnit();
		for (int i=1;i<=listUnit.size();i++){
			list.add(getResources().getStringArray(R.array.unitarray)[listUnit.get(i)-1]);
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		unitdep.setAdapter(dataAdapter);
		if (list.contains(selectedunit)){
			unitdep.setSelection(list.indexOf(selectedunit));
		}
		else {
			unitdep.setSelection(0);
		}
		//mise à  jour méridien
		Spinner spmeri = (Spinner) findViewById(R.id.spinner_meriddep);
		list = new ArrayList<String>();
		Iterator<Integer> iter=data.listLGO.keySet().iterator();
		Integer current;
		Integer indexunitreg=0;
		while (iter.hasNext()){
			current=iter.next();
			list.add(data.listLGO.get(current).getNom());
			if (data.listREG.get(numreg).getLGO()==current){
				indexunitreg=list.size()-1;
			}
		}
		dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spmeri.setAdapter(dataAdapter);
		spmeri.setSelection(indexunitreg);
		
	}
	else if (spdep.getSelectedItem().toString()==getString(R.string.typecoordplan)){
		//afficher proj, cacher unit
		llunit.setVisibility(LinearLayout.GONE);
		llproj.setVisibility(LinearLayout.VISIBLE);
		//mise à  jour des projs
		Spinner spregdep = (Spinner) findViewById(R.id.spinner_systdepart);
		String reg=spregdep.getSelectedItem().toString();
		List<String> list = new ArrayList<String>();
		Spinner spproj = (Spinner) findViewById(R.id.spinner_projdep);
		int numreg=data.getRegNum(reg);
		for (int i=1;i<=data.listPROJ.size();i++){
			if (data.listPROJ.get(i).getREG()==numreg){
				list.add(data.listPRC.get(data.listPROJ.get(i).getPRC()).getNom());
			}
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spproj.setAdapter(dataAdapter);
	}
	else {
		//cacher unit et proj
		llunit.setVisibility(LinearLayout.GONE);
		llproj.setVisibility(LinearLayout.GONE);
	}
}
public void updateunitprojarr(){
	Spinner spdep = (Spinner) findViewById(R.id.spinner_typcoordarr);
	Spinner unitdep = (Spinner) findViewById(R.id.spinner_unitarr);
	LinearLayout llunit = (LinearLayout) findViewById(R.id.linearLayoutUnitarr);
	LinearLayout llproj = (LinearLayout) findViewById(R.id.linearLayoutprojectiondarr);
	if (spdep.getSelectedItem().toString()==getString(R.string.typecoordgeo)){
		//afficher unit, cacher proj
		llunit.setVisibility(LinearLayout.VISIBLE);
		llproj.setVisibility(LinearLayout.GONE);
		//mise à  jour des unités
		Spinner spregdep=(Spinner) findViewById(R.id.spinner_systarrivee);
		String reg=spregdep.getSelectedItem().toString();
		List<String> list = new ArrayList<String>();
		int numreg=data.getRegNum(reg);
		HashMap<Integer, Integer> listUnit=data.listUNIT.get(numreg).getListUnit();
		for (int i=1;i<=listUnit.size();i++){
			list.add(getResources().getStringArray(R.array.unitarray)[listUnit.get(i)-1]);
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		unitdep.setAdapter(dataAdapter);
		//mise à  jour méridien
		Spinner spmeri = (Spinner) findViewById(R.id.spinner_meridarr);
		list = new ArrayList<String>();
		Iterator<Integer> iter=data.listLGO.keySet().iterator();
		Integer current;
		Integer indexunitreg=0;
		while (iter.hasNext()){
			current=iter.next();
			list.add(data.listLGO.get(current).getNom());
			if (data.listREG.get(numreg).getLGO()==current){
				indexunitreg=list.size()-1;
			}
		}
		dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spmeri.setAdapter(dataAdapter);
		spmeri.setSelection(indexunitreg);
	}
	else if (spdep.getSelectedItem().toString()==getString(R.string.typecoordplan)){
		//afficher proj, cacher unit
		llunit.setVisibility(LinearLayout.GONE);
		llproj.setVisibility(LinearLayout.VISIBLE);
		//mise à  jour des projs
		Spinner spregdep = (Spinner) findViewById(R.id.spinner_systarrivee);
		String reg=spregdep.getSelectedItem().toString();
		List<String> list = new ArrayList<String>();
		Spinner spproj = (Spinner) findViewById(R.id.spinner_projarr);
		int numreg=data.getRegNum(reg);
		for (int i=1;i<=data.listPROJ.size();i++){
			if (data.listPROJ.get(i).getREG()==numreg){
				list.add(data.listPRC.get(data.listPROJ.get(i).getPRC()).getNom());
			}
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spproj.setAdapter(dataAdapter);
	}
	else {
		//cacher unit et proj
		llunit.setVisibility(LinearLayout.GONE);
		llproj.setVisibility(LinearLayout.GONE);
	}
}

public void updatecalc(){
	
	Spinner type = (Spinner) findViewById(R.id.spinner_typcoorddep);
	Spinner unit = (Spinner) findViewById(R.id.spinner_unitdep);
	String nomtype;
	try {
		nomtype = type.getSelectedItem().toString();
	} catch (Exception e) {
		nomtype="";
	}
	
	String nomunit;
	try {
		nomunit = unit.getSelectedItem().toString();
	} catch (Exception e) {
		nomunit="";
	}
	LinearLayout cart = (LinearLayout) findViewById(R.id.linearLayoutcalcCart);
	LinearLayout geo1 = (LinearLayout) findViewById(R.id.linearLayoutcalcgeo1);
	LinearLayout geo2 = (LinearLayout) findViewById(R.id.linearLayoutcalcgeo2);
	LinearLayout geo3 = (LinearLayout) findViewById(R.id.linearLayoutcalcgeo3);
	LinearLayout plan = (LinearLayout) findViewById(R.id.linearLayoutcalcplan);
	LinearLayout alti = (LinearLayout) findViewById(R.id.linearLayoutcalcalti);
	

	if (nomtype.equals(getString(R.string.typecoordcart))){
		cart.setVisibility(LinearLayout.VISIBLE);
		geo1.setVisibility(LinearLayout.GONE);
		geo2.setVisibility(LinearLayout.GONE);
		geo3.setVisibility(LinearLayout.GONE);
		plan.setVisibility(LinearLayout.GONE);
		alti.setVisibility(LinearLayout.GONE);
	}
	else if (nomtype.equals(getString(R.string.typecoordgeo))){

		cart.setVisibility(LinearLayout.GONE);
		plan.setVisibility(LinearLayout.GONE);
		
		if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[0]) ||
			nomunit.equals(getResources().getStringArray(R.array.unitarray)[1]) ||
			nomunit.equals(getResources().getStringArray(R.array.unitarray)[2]) ||
			nomunit.equals(getResources().getStringArray(R.array.unitarray)[3]) ||
			nomunit.equals(getResources().getStringArray(R.array.unitarray)[4]) ||
			nomunit.equals(getResources().getStringArray(R.array.unitarray)[5])){
			
			//Un champs
			geo1.setVisibility(LinearLayout.VISIBLE);
			geo2.setVisibility(LinearLayout.GONE);
			geo3.setVisibility(LinearLayout.GONE);
			
			
			//unità©
			TextView unitlon1 = (TextView) findViewById(R.id.unitlon1);
			TextView unitlat1 = (TextView) findViewById(R.id.unitlat1);
			if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[0])){
				unitlon1.setText("rad");
				unitlat1.setText("rad");
			}
			else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[1])){
				unitlon1.setText("°");
				unitlat1.setText("°");
			}
			else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[2])){
				unitlon1.setText("gon");
				unitlat1.setText("gon");
			}
			else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[3])){
				unitlon1.setText("h");
				unitlat1.setText("h");
			}
			else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[4])){
				unitlon1.setText("\"");
				unitlat1.setText("\"");
			}
			else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[5])){
				unitlon1.setText("s");
				unitlat1.setText("s");
			}
			
			
		}
		else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[9]) ||
			nomunit.equals(getResources().getStringArray(R.array.unitarray)[10])){
			//Trois champs
			geo1.setVisibility(LinearLayout.GONE);
			geo2.setVisibility(LinearLayout.GONE);
			geo3.setVisibility(LinearLayout.VISIBLE);
			
			//unità©
			TextView unitlon1 = (TextView) findViewById(R.id.unitlon31);
			TextView unitlon2 = (TextView) findViewById(R.id.unitlon32);
			TextView unitlon3 = (TextView) findViewById(R.id.unitlon33);
			TextView unitlat1 = (TextView) findViewById(R.id.unitlat31);
			TextView unitlat2 = (TextView) findViewById(R.id.unitlat32);
			TextView unitlat3 = (TextView) findViewById(R.id.unitlat33);
			if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[9])){
				unitlon1.setText("°");
				unitlon2.setText("'");
				unitlon3.setText("\"");
				unitlat1.setText("°");
				unitlat2.setText("'");
				unitlat3.setText("\"");
			}
			else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[10])){
				unitlon1.setText("h");
				unitlon2.setText("mn");
				unitlon3.setText("s");
				unitlat1.setText("h");
				unitlat2.setText("mn");
				unitlat3.setText("s");
			}
		}
		else if (nomunit.equals(getResources().getStringArray(R.array.unitarray)[11])){
			//Deux champs
			geo1.setVisibility(LinearLayout.GONE);
			geo2.setVisibility(LinearLayout.VISIBLE);
			geo3.setVisibility(LinearLayout.GONE);
			//unité
			TextView unitlon1 = (TextView) findViewById(R.id.unitlon21);
			TextView unitlon2 = (TextView) findViewById(R.id.unitlon22);
			TextView unitlat1 = (TextView) findViewById(R.id.unitlat21);
			TextView unitlat2 = (TextView) findViewById(R.id.unitlat22);
			unitlon1.setText("°");
			unitlon2.setText("'");
			unitlat1.setText("°");
			unitlat2.setText("'");
			
		}
		String  selectedaltidep = (String) ((Spinner) findViewById(R.id.spinner_altidep)).getSelectedItem();
		if (selectedaltidep.equals(R.string.noinfo)){
			alti.setVisibility(LinearLayout.GONE);
		} else {
			alti.setVisibility(LinearLayout.VISIBLE);
		}

	}
	else if (nomtype.equals(getString(R.string.typecoordplan))){
		cart.setVisibility(LinearLayout.GONE);
		geo1.setVisibility(LinearLayout.GONE);
		geo2.setVisibility(LinearLayout.GONE);
		geo3.setVisibility(LinearLayout.GONE);
		plan.setVisibility(LinearLayout.VISIBLE);
		
		String  selectedaltidep = (String) ((Spinner) findViewById(R.id.spinner_altidep)).getSelectedItem();
		if (selectedaltidep.equals(R.string.noinfo)){
			alti.setVisibility(LinearLayout.GONE);
		} else {
			alti.setVisibility(LinearLayout.VISIBLE);
		}
	}
}

public void updatealtidep(){
	
	Spinner regdep = (Spinner) findViewById(R.id.spinner_systdepart);
	String reg_dep = (String) regdep.getSelectedItem();
	
	Spinner typcoordspin = (Spinner) findViewById(R.id.spinner_typcoorddep);
	String typcoorddep = (String) typcoordspin.getSelectedItem();
	
	LinearLayout LinLay_altidep = (LinearLayout) findViewById(R.id.linearLayoutaltidep);
	if (typcoorddep.equals(getString(R.string.typecoordcart))){
		//En départ, on a des coord cartésiennes
		LinLay_altidep.setVisibility(LinearLayout.GONE);
	} else {
		LinLay_altidep.setVisibility(LinearLayout.VISIBLE);
	}
	
	Spinner altidep = (Spinner) findViewById(R.id.spinner_altidep);
	Integer indreg= data.getRegNum(reg_dep);
	
	Integer indrega = data.getRegNum((String) ((Spinner) findViewById(R.id.spinner_systarrivee)).getSelectedItem());
	
	String select = (String) altidep.getSelectedItem();
	List<String> list = new ArrayList<String>();
	
	//Ajout pas d'info et hauteur ellipsoidale
	list.add(getResources().getString(R.string.noinfo));
	if (data.listREG.get(indreg).getDim()==3){
		list.add(getResources().getString(R.string.he));
	}

	Set<Integer> keyset=data.listGR1D.keySet();
	Iterator<Integer> iter = keyset.iterator();
	Integer current;
	while (iter.hasNext()){
		current=iter.next();
		if (data.listGR1D.get(current).getREG()==indreg || data.listGR1D.get(current).getREG()==indrega){
			Integer currentbis;
			for (Iterator<Integer> iterbis=data.listGR1D.get(current).getListREA().keySet().iterator();iterbis.hasNext();){
				currentbis= iterbis.next();
				//On ajout sans vérification
				list.add(data.listREA.get(data.listGR1D.get(current).getListREA().get(currentbis)).getNom());
				
			}
		}
	}

	ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
	dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	altidep.setAdapter(dataAdapter);
	altidep.setSelection(0);
	for (int i=0;i<list.size();i++){
		if (list.get(i)==select){
			altidep.setSelection(i);
			break;
		}
	}
	
}

public void updatealtiarr(){
	
	Spinner regarr = (Spinner) findViewById(R.id.spinner_systarrivee);
	String reg_arr = (String) regarr.getSelectedItem();
	
	Spinner regdep = (Spinner) findViewById(R.id.spinner_systdepart);
	String reg_dep = (String) regdep.getSelectedItem();
	
	Spinner typcoordspin = (Spinner) findViewById(R.id.spinner_typcoordarr);
	String typcoordarr = (String) typcoordspin.getSelectedItem();
	
	LinearLayout LinLay_altiarr = (LinearLayout) findViewById(R.id.linearLayoutaltiarr);
	if (typcoordarr.equals(getString(R.string.typecoordcart))){
		//En départ, on a des coord cartésiennes
		LinLay_altiarr.setVisibility(LinearLayout.GONE);
	} else {
		LinLay_altiarr.setVisibility(LinearLayout.VISIBLE);
	}
	
	Spinner altidep = (Spinner) findViewById(R.id.spinner_altidep);
	Spinner altiarr = (Spinner) findViewById(R.id.spinner_altiarr);
	Integer indreg= data.getRegNum(reg_arr);
	Integer indregdep= data.getRegNum(reg_dep);
	String select = (String) altiarr.getSelectedItem();
	List<String> list = new ArrayList<String>();
	
	//Ajout pas d'info et hauteur ellipsoidale
	list.add(getResources().getString(R.string.noinfo));
	
	String typcorrdep = (String) ((Spinner) findViewById(R.id.spinner_typcoorddep)).getSelectedItem();
	if (((String) altidep.getSelectedItem())!=getString(R.string.noinfo) || typcorrdep == getString(R.string.typecoordcart)){
	
	if (data.listREG.get(indreg).getDim()==3){
		list.add(getResources().getString(R.string.he));
	}

	Set<Integer> keyset=data.listGR1D.keySet();
	Iterator<Integer> iter = keyset.iterator();
	Integer current;
	while (iter.hasNext()){
		current=iter.next();
		if (data.listGR1D.get(current).getREG()==indreg || data.listGR1D.get(current).getREG()==indregdep){
			Integer currentbis;
			for (Iterator<Integer> iterbis=data.listGR1D.get(current).getListREA().keySet().iterator();iterbis.hasNext();){
				currentbis= iterbis.next();
				//On ajout sans vérification
				list.add(data.listREA.get(data.listGR1D.get(current).getListREA().get(currentbis)).getNom());
				
			}
		}
	}
	}
	ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, list);
	dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	altiarr.setAdapter(dataAdapter);
	altiarr.setSelection(0);
	for (int i=0;i<list.size();i++){
		if (list.get(i)==select){
			altiarr.setSelection(i);
			break;
		}
	}
	
}

public void updatealti(){
	updatealtidep();
	updatealtiarr();
}
}
